<template>
  <div class="topnav" v-if="isShow">
    <div @click="top"><i class="iconfont icon-zhiding"></i></div>
  </div>
</template>

<script>
export default {
  name: "topnav",
  data() {
    return {
      isShow: false
    };
  },
  mounted() {
    window.addEventListener("scroll", this.scrollToTop); // 创建距离顶部位置
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollToTop); // 销毁（防止报错）
  },
  methods: {
    scrollToTop() {
      var scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      if (scrollTop > 300) {
        // 大于300距离显示隐藏
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    // 返回顶部
    top() {
      setTimeout(() => {
        let ispeed = Math.floor(-this.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          this.scrollTop + ispeed;
      }, 16);
    }
  }
};
</script>

<style lang="scss">
.topnav {
  width: 44px;
  height: 44px;
  position: fixed;
  bottom: 50px;
  right: 54px;
  text-align: center;
  color: #ffffff;
  padding-top: 8px;
  background-color: #b21315;
  i {
    font-size: 30px;
  }
}
</style>
